package com.syw.houmao.main.connect;

/**
 * Created by Administrator on 2016/10/19.
 */

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2016/9/23.
 */
public class OkHttpHelperUtils {
    private static OkHttpHelperUtils okHttpHelperUtils;
    private static OkHttpClient okHttpClient;
    private static Object mLock = new Object();



    public static OkHttpHelperUtils getOkHttpHelperUtils() {
        if (okHttpHelperUtils == null) {
            synchronized (mLock) {
                if (okHttpHelperUtils == null) {
                    okHttpHelperUtils = new OkHttpHelperUtils();
                }
            }
        }
        return okHttpHelperUtils;
    }

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            synchronized (mLock) {
                if (okHttpClient == null) {
                    okHttpClient = new OkHttpClient();
                }
            }
        }
        return okHttpClient;
    }

    private Request getRequest(String url) {
        Request request = new Request.Builder().url(url).build();
        return request;
    }

    private Response getResponse(String url) throws IOException {
        Response response = getOkHttpClient().newCall(getRequest(url)).execute();
        return response;
    }

    private ResponseBody getResponseBody(String url) throws IOException {
        Response response = getResponse(url);
        if (response.isSuccessful()) {
            ResponseBody body = response.body();
            return body;
        }
        return null;
    }
    public static String getStringFromUrl(String url) throws IOException {
        ResponseBody body = getOkHttpHelperUtils().getResponseBody(url);
        if(body!=null){
            String result = body.string();

            return result;
        }
        return null;
    }
    public static byte[] getArrayFromUrl(String url) throws IOException {
        ResponseBody body = getOkHttpHelperUtils().getResponseBody(url);
        if(body!=null){
            byte[] bytes = body.bytes();
            return bytes;
        }
        return null;
    }
    public static InputStream getStreamFromUrl(String url) throws IOException {
        ResponseBody body = getOkHttpHelperUtils().getResponseBody(url);
        if(body!=null){
            InputStream inputStream = body.byteStream();
            return inputStream;
        }
        return null;
    }
    /*
        异步get请求
    * */
    public static void AsyncRequestGet(String url, Callback callback){
        Request request = okHttpHelperUtils.getRequest(url);
        getOkHttpClient().newCall(request).enqueue(callback);
    }
}